<?php

namespace App\Http\Controllers\supplier;

use App\Http\Controllers\Controller;
use App\Http\Controllers\supplier\TestController;
use App\Models\Admin\InterfaceConfiguration;
use App\Models\Admin\SupplierInterfacePermissions;
use App\Models\Mysql\CyclePercentage;
use App\Models\Mysql\XnGoodsCarmyType;
use App\Models\Mysql\XnGoodsTimeIsUp;
use App\Models\Mysql\XnMerchant;
use App\Models\Mysql\XnMerchantGoodsInvoicing;
use App\Models\Mysql\XnMerchantGoodsTimeIsUp;
use App\Models\Mysql\XnSupplierGoods;
use App\Models\Mysql\XnSupplierGoodsFullyChargedRelation;
use App\Models\Mysql\XnSupplierGoodsMerchantRelation;
use App\Models\Mysql\XnSupplierGoodsRelation;
use App\Models\Mysql\XuGoodsBrand;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use App\Models\Mysql\XnTerraceInfo;
use Carbon\Carbon;
use App\Jobs\SupplierGoodsTImeIsUp;
use App\Jobs\SupplierGoodsTImePrice;
use App\Jobs\MerchantGoodsTimePrice;
use App\Jobs\MerchantGoodsTimeIsUp;
use Illuminate\Support\Facades\Redis;

class SupplierGoodsController extends Controller
{
    //供应商仓库
    public function warehouse(Request $request){
        $params = $request->all();
        $where =[];
        if (!empty($params['goods_name'])){
            $where[] = ['goods_name','like','%'.$params['goods_name'].'%'];
        }
        if (!empty($params['goods_code'])){
            $where[] = ['id',$params['goods_code']];
        }
        $where[] = ['is_up',2];
        $res = XnSupplierGoods::where($where)->orderBy('time','desc')->paginate(10);
        $this->belong($res);
        if (!$res){
            return $this->sendError('查询失败');
        }
        return  $this->sendResponse($res,'查询成功');
    }
    //供应商上架商品
    public function is_up(Request $request){
        $params = $request->all();
        if (empty($params['id'])){
            return $this->sendError('商品id不能为空');
        }
        if (empty($params['is_up'])){
            return $this->sendError('商品状态不能为空');
        }
        $id = explode(',',$params['id']);
        foreach ($id as $k=>$v){
            $res = XnSupplierGoods::where('id',$v)->update(['is_up'=>$params['is_up']]);
        }
        if (!$res){
            return $this->sendError('操作失败');
        }
        return  $this->sendResponse([],'操作成功');
    }
    //供应商删除商品
    public function del(Request $request){
        $params = $request->all();
        if (empty($params['id'])){
            return $this->sendError('商品id不能为空');
        }
        $res = XnSupplierGoods::where('id',$params['id'])->delete();
        if (!$res){
            return $this->sendError('删除失败');
        }
        return  $this->sendResponse([],'删除成功');
    }
    //供应商商品编辑
    public function edit(Request $request){
        $params = $request->all();
        if (empty($params['goods_name']) || empty($params['unit_price'])|| empty($params['price'])|| empty($params['brand_id']) || empty($params['max_price']) || empty($params['id'])){
            return $this->sendError('参数不能为空');
        }
        $array = [
            'goods_name'=>$params['goods_name'],
            'unit_price'=>$params['unit_price'],
            'price'=>$params['price'],
            'brand_id'=>$params['brand_id'],
            'max_price'=>$params['max_price'],
        ];
        $res = XnSupplierGoods::where('id',$params['id'])->update($array);
        if (!$res){
            return $this->sendError('编辑失败');
        }
        return  $this->sendResponse([],'编辑成功');
    }
    //供应商商品添加
    public function add(Request $request){
        $params = $request->all();

        if (empty($params['goods_name'])){
            return $this->sendError('商品名称不可为空');
        }
        if (empty($params['unit_price'])){
            return $this->sendError('商品进价不可以为空');
        }
        if (empty($params['price'])){
            return $this->sendError('商品销售价不可以为空');
        }
        $array = [
            'goods_code'=>$params['goods_code'] ?? 'xn'.substr(uniqid(),-8),//第三方编码
//            'ids'=>$params[''],//平台编码
            'goods_belong'=>$params['goods_belong'] ?? 0,
            'goods_name'=>$params['goods_name'],
            'unit_price'=>$params['unit_price'],
            'price'=>$params['price'],
            'time'=>date('Y-m-d H:i:s'),
            'productId'=>$params['productId'] ?? '',
            'goods_type'=>$params['type'],
            'o_type'=>$params['o_type']??0
        ];

        $res = XnSupplierGoods::insert($array);
        if (!$res){
            return $this->sendError('添加失败');
        }
        return  $this->sendResponse([],'添加成功请到仓库进行编辑');
    }
    //供应商商品权限列表
    public function authority(){
        $user = auth('support')->user();
        $res = SupplierInterfacePermissions::where('sid',$user['id'])->select('interface_id as goods_belong')->paginate(20);
        $res = json_decode(json_encode($res),true);

        foreach ($res['data'] as $k=>$v){
            $res['data'][$k]['title'] = InterfaceConfiguration::where('id',$v['goods_belong'])->value('title');
            $type = XnTerraceInfo::where('sid',$v['goods_belong'])->first();
            if (empty($type['datas'])){
               unset($res[$k]);
            }
        }
        if (!$res){
            return $this->sendError('查询失败');
        }
        return  $this->sendResponse($res,'查询成功');
    }
    //供应商商品列表
    public function list(Request $request){
        $params = $request->all();
        $user = auth('support')->user();
        if (empty($params['release'])){
            return $this->sendError('发布状态不可为空');
        }
        $where = [];
        if (!empty($params['goods_name'])){
            $where[] = ['goods_name','like','%'.$params['goods_name'].'%'];
        }
        if (!empty($params['goods_code'])){
            $where[] = ['goods_code',$params['goods_code']];
        }
        if (!empty($params['release'])){
            $where[] = ['release',$params['release']];
        }
        if(!empty( $params['brand_id'])){
            $collem = 'brand_id';
            $easn = '=';
            $val =  $params['brand_id'];
        }else{
            $collem = 'brand_id';
            $easn = '!=';
            $val = null;
        }
        $where[]=['is_up',1];
        $res = XnSupplierGoods::where($where)->where($collem,$easn,$val)->orderBy('price')->paginate(10);
        $redis = new \redis();
        $redis->connect('127.0.0.1', 6379);//连接redis
        foreach ($res as $k=>$v){
            $v['supplier_goods_regular_price'] =json_decode( $redis->get($user->business_number.'SupplierGoodsTImePrice'.$v['id']),true);
        }
        $this->belong($res);
        if (!$res){
            return $this->sendError('查询失败');
        }
        return  $this->sendResponse($res,'查询成功');
    }
    //供应商设置定时上下架
    public function regular_release(Request $request){
        $params = $request->all();

        $day= explode(',',$params['day']);
        if ($params['status'] == 1 && empty($params['day'])){
            return $this->sendError('请选择时间周期');
        }
        if ($params['status'] == 2){
            XnGoodsTimeIsUp::where('goods_id',$params['goods_id'])->delete();
            XnSupplierGoods::where('id',$params['goods_id'])->update(['timing_is_up'=>2]);
            return $this->sendResponse([],'设置成功');
        }
        if (empty($params['day'])){
            XnGoodsTimeIsUp::where('goods_id',$params['goods_id'])->delete();
            return $this->sendResponse([],'设置成功');
        }
        XnGoodsTimeIsUp::where('goods_id',$params['goods_id'])->delete();
        $array = [];
        foreach ($day as $k=>$v){
            $data = [
                'goods_id'=>$params['goods_id'],
                'day'=>$v,
                'shelftime'=>strtotime($params['shelftime']),
                'offshelftime'=>strtotime($params['offshelftime']),
                'type'=>$params['type']
            ];
            $array[] = $data;
        }
        XnSupplierGoods::where('id',$params['goods_id'])->update(['timing_is_up'=>$params['status']]);
        $res =XnGoodsTimeIsUp::insert($array);
        if (!$res){
            return $this->sendError('设置失败');
        }else{
            $week = date("w");
            $info = XnGoodsTimeIsUp::where('day',$week)->where('goods_id',$params['goods_id'])->first();
            $info = json_decode(json_encode($info),true);
//            var_dump($info);
            if (!empty($info)){
                $time = date('H:i:s',time());//当前时间
                $start_time = date('H:i:s', $info['shelftime']);
                $end_time = date('H:i:s',$info['offshelftime']);

                $Remaining_time1 = strtotime($start_time) - strtotime($time);
                $Remaining_time2 = strtotime($end_time) - strtotime($time);
                $data1 = [];
                $data2 = [];
                $goodsInfo = XnSupplierGoods::where('id',$params['goods_id'])->first();
                if ($goodsInfo['release'] == 0){
                    return $this->sendResponse([],'设置成功');
                }
                if ($info['type'] == 1){ //维护时间
                    if ($goodsInfo['release'] == 1){
                        $res = $this->rangeTime($start_time,$end_time);
                        if ($res == true){
                            XnSupplierGoods::where('id',$params['goods_id'])->update(['release'=>3]);
                        }
                    }elseif ($goodsInfo['release'] == 3){
                        $res = $this->rangeTime($start_time,$end_time);
                        if ($res == false){
                            XnSupplierGoods::where('id',$params['goodsId'])->update(['release'=>1]);
                        }
                    }
                    $data1 = [
                        'goods_id'=>$info['goods_id'],
                        'status'=>3,
                        'db'=>request()->get('db', 'supplier')
                    ];
                    $data2 = [
                        'goods_id'=>$info['goods_id'],
                        'status'=>1,
                        'db'=>request()->get('db', 'supplier')
                    ];
                    SupplierGoodsTImeIsUp::dispatch($data2)->delay(Carbon::now()->addSeconds($Remaining_time2))->onConnection('redis')->onQueue('SupplierGoodsTimeIsUp');//下架时间
                }
                if ($info['type'] == 2){
                    if ($goodsInfo['release'] == 1){
                        $res = $this->rangeTime($start_time,$end_time);
                        if ($res == false){
                            XnSupplierGoods::where('id',$params['goods_id'])->update(['release'=>3]);
                        }
                    }elseif($goodsInfo['release'] == 3){
                        $res = $this->rangeTime($start_time,$end_time);
                        if ($res == true){
                            XnSupplierGoods::where('id',$params['goods_id'])->update(['release'=>1]);
                        }
                    }
                    $data1 = [
                        'goods_id'=>$info['goods_id'],
                        'status'=>1,
                        'db'=>request()->get('db', 'supplier')
                    ];
                    $data2 = [
                        'goods_id'=>$info['goods_id'],
                        'status'=>3,
                        'db'=>request()->get('db', 'supplier')
                    ];
                    SupplierGoodsTImeIsUp::dispatch($data2)->delay(Carbon::now()->addSeconds($Remaining_time2))->onConnection('redis')->onQueue('SupplierGoodsTimeIsUp');//下架时间
                }
                if ($info['type'] == 0){
                    return $this->sendResponse([],'设置成功');
                }
                if ($Remaining_time1 < 0 || $Remaining_time2< 0){
                    return $this->sendResponse([],'设置成功');
                }
                SupplierGoodsTImeIsUp::dispatch($data1)->delay(Carbon::now()->addSeconds($Remaining_time1))->onConnection('redis')->onQueue('SupplierGoodsTimeIsUp');//上架时间
                SupplierGoodsTImeIsUp::dispatch($data2)->delay(Carbon::now()->addSeconds($Remaining_time2))->onConnection('redis')->onQueue('SupplierGoodsTimeIsUp');//下架时间
            }
            return $this->sendResponse([],'设置成功');
        }

    }
    //供应商设置定时上下架列表信息
    public function regular_release_list(Request $request){
        $params = $request->all();
        $goods = XnSupplierGoods::where('id',$params['goods_id'])->value('timing_is_up');
        $res = XnGoodsTimeIsUp::where('goods_id',$params['goods_id'])->get();
        $res = json_decode(json_encode($res),true);
        if (empty($res)){
            return $this->sendError('没有设置');
        }
        $week = [];
        foreach ($res as $k=>$v){
            $week[] = $v['day'];
            $res['shelftime'] = $v['shelftime'];
            $res['offshelftime'] = $v['offshelftime'];
            $res['type'] = $v['type'];
        }
        $data = [
            'week'=>implode(',',$week),
            'shelftime'=>date('H:i:s', $res['shelftime']),
            'offshelftime'=>date('H:i:s',$res['offshelftime']),
            'type' => $res['type'],
            'timing_is_up'=>$goods
        ];
        if (!$res){
            return $this->sendError('没有设置');
        }else{
            return $this->sendResponse($data,'查询成功');
        }
    }
    //供应商设置定时改价
    public function regular_price(Request $request){
        $params = $request->all();

        $user = auth('support')->user();//获取供应商信息
        $startDate =date('Y-m-d H:i:s');//现在的时间
        $endDate = $params['time'];//要修改的时间
        $time=floor((strtotime($endDate)-strtotime($startDate)));
        $str = strpos($time,'-');
        if ($str === 0){
            return $this->sendError('请选择正确的时间');
        }
        $data = [
            'id'=>$params['id'],//商品id
            'unit_price'=>$params['unit_price'],//进货价
            'price'=>$params['price'],//销售价
            'max_price'=>$params['max_price'],//价格上线
            'business_number'=>$user->business_number,
            'db'=>request()->get('db', 'supplier')
        ];
        SupplierGoodsTImePrice::dispatch($data)->delay(Carbon::now()->addSeconds($time))->onConnection('redis')->onQueue('SupplierGoodsTImePrice');
        $redis = new \redis();
        $redis->connect('127.0.0.1', 6379);//连接redis
        $info = [
            'id'=>$params['id'],//商品id
            'unit_price'=>$params['unit_price'],//进货价
            'price'=>$params['price'],//销售价
            'max_price'=>$params['max_price'],//价格上线
            'time'=>$endDate,
            'business_number'=>$user->business_number,
        ];
        $key = $user->business_number.'SupplierGoodsTImePrice'.$data['id'];
        $value = json_encode($info);//用手机号作为v值
        $redis->set($key, $value, 86400);//设置的24小时有效期
        return $this->sendResponse([],'将在'.$endDate.'修改此商品价格');

    }
    //供应商撤销定时改价
    public function regular_price_revoke(Request $request){
        $params = $request->all();
        $user = auth('support')->user();//获取供应商信息
        $redis = new \redis();
        $redis->connect('127.0.0.1', 6379);//连接redis
        $key = $user->business_number.'SupplierGoodsTImePrice'.$params['id'];
        $redis->del($key);//删除定时的key
        return $this->sendResponse([],'撤销成功');
    }
    //供应商发布取消发布商品
    public function release(Request $request){
        $parmas = $request->all();
        if (empty($parmas['id'])){
            return $this->sendError('商品id不能为空');
        }
        if (empty($parmas['status'])){
            return $this->sendError('商品状态不能为空');
        }
        $id = explode(',',$parmas['id']);
        $res = XnSupplierGoods::wherein('id',$id)->update(['release'=>$parmas['status']]);
        if (!$res){
            return $this->sendError('操作失败');
        }
        return  $this->sendResponse([],'操作成功');
    }
    //供应商关联子商品列表
    public function association(Request $request){
        $params = $request->all();
        $search = $request->post('search','');
        $where = [];
        if (isset($search['keyword']) && !empty($search['keyword'])) {
            $where = function($query) use($search){
                $query->where('g.goods_name', 'like', '%'.$search['keyword'].'%')

                    ->orWhere('g.goods_belong', 'like', '%'.$search['keyword'].'%')
                    ->orWhere('g.goods_code', 'like', '%'.$search['keyword'].'%');
            };
        }
//        DB::connection()->enableQueryLog();
        $res = Db::connection( request()->get('db', null))->table('xn_supplier_goods as g')
            ->leftjoin('xn_supplier_goods_relation as r', function($join) use ($params) {
                $join->on('g.id', '=', 'r.r_gid')->where('r.g_id', '=', $params['goods_id']);
            })
            ->where('g.goods_belong', '!=', 2)
            ->where('g.goods_belong', '!=', 3)
            ->where('g.is_up', '=', 1)
            ->where('g.release', '!=', 3)
            ->where('g.goods_belong','!=',0)
            ->where('g.brand_id','=',$params['brand_id'])
            ->where($where)
            ->orderBy('g.unit_price')
            ->when($params['type'], function($query) use($params){
                return $params['type'] == 2 ? $query->whereNull('r.id') : $query->whereRaw('IF(ISNULL(r.id), false, true)')->orderBy('r.sort','desc');
            })
            ->select('g.o_type','g.goods_name','r.percentage','r.sort','r.id as r_id','g.id', 'g.goods_code','g.goods_code', 'g.unit_price', 'g.goods_belong', 'g.max_price', 'g.release', Db::raw('IF(ISNULL(r.id), 2 , 1) as is_relation'))
            ->paginate(10);
//        $res = DB::getQueryLog();
        $percentage_s = 0;
        $res = json_decode(json_encode($res),true);
        foreach ($res['data'] as $k=>$v){
            $res['data'][$k]['percentage_s'] = ($percentage_s+$v['percentage']);
            if ($v['o_type'] != 0){
                $res['data'][$k]['goods_belong'] = XnGoodsCarmyType::where('type',$v['goods_belong'])->value('name');
            }else{
                $res['data'][$k]['goods_belong'] = InterfaceConfiguration::where('id',$v['goods_belong'])->value('title');
            }
        }
        if (!$res){
            return $this->sendError('查询失败');
        }
        return $this->sendResponse($res, '查询成功');

    }
    //供应商关联子商品操作
    public function association_edit(Request $request){
        $params = $request->all();
        if (empty($params['type'])){
            return $this->sendError('操作状态不能为空');
        }
        if (empty($params['g_id'])){
            return $this->sendError('商品id不能为空');
        }
        if (empty($params['r_gid'])){
            return $this->sendError('被关联商品id不能为空');
        }

        if ($params['type'] == 1){
            $array = [
                'g_id'=>$params['g_id'],
                'r_gid'=>$params['r_gid']
            ];
            $status = XnSupplierGoodsRelation::where(['g_id'=>$params['g_id'],'r_gid'=>$params['r_gid']])->first();
            if (!empty($status)){
                return $this->sendError('该商品已经关联');
            }
            $res =XnSupplierGoodsRelation::insert($array);
            if (!$res){
                return $this->sendError('关联失败');
            }
            return  $this->sendResponse([],'关联成功');
        }elseif ($params['type'] ==2 ){
            $res = XnSupplierGoodsRelation::where('id',$params['r_id'])->delete();
            if (!$res){
                return $this->sendError('操作频繁');
            }
            return  $this->sendResponse([],'取消成功');
        }
        return $this->sendError('参数无效');
    }
    //子商品置顶
    public function child_goods_topping(Request $request){
        $params = $request->all();
        if (empty($params['r_id'])){
            return $this->sendError('id不能为空');
        }

        $res = XnSupplierGoodsRelation::where('id',$params['r_id'])->update(['sort'=>$params['type']]);
        if (!$res){
            return $this->sendError('操作失败');
        }
        return $this->sendResponse([],'操作成功');
    }
    //子商品设置百分比· /
    public function child_goods_percentage(Request $request){
        $params = $request->all();
        $row = XnSupplierGoodsRelation::where('id',$params['r_id'])->first();
        if (!$row) {
            return $this->sendError('设置失败');
        }
        $row = collect($row)->toArray();
        if ($row['percentage'] == $params['percentage']) {
            return $this->sendError('未做更改');
        }
        DB::connection(request()->get('db', 'supplier'))->beginTransaction();
        try {
            $res = XnSupplierGoodsRelation::where('id',$row['id'])->update(['percentage'=>$params['percentage']]);
            if (!$res){
                throw new \Exception('设置失败');
            }
           CyclePercentage::where('pid', $row['r_gid'])
                ->where('role', 1)
                ->delete();

            DB::connection(request()->get('db', 'supplier'))->commit();
        } catch (\Throwable $e) {
            DB::connection(request()->get('db', 'supplier'))->rollBack();
            return $this->sendError($e->getMessage());
        }
        return $this->sendResponse([],'设置成功');
    }
    //商户开票商户列表
    public function merchant_invoicing_list(Request $request){
        $params = $request->post();
        $wheres = [];
        $wheres[]=['merchant_type',2];
        if (!empty($params['nickname'])){
            $wheres[] = ['nickname', 'like', '%'.$params['nickname'].'%'];
        }
        if (!empty($params['merchant_number'])){
            $wheres[] = ['merchant_number', $params['merchant_number']];
        }
        if (!empty($params['phone'])){
            $wheres[] = ['phone', $params['phone']];
        }

       $res = XnMerchant::where($wheres)->select('nickname','merchant_number')->paginate(30);
        if (!$res){
            return $this->sendError('查询失败');
        }
        return  $this->sendResponse($res,'查询成功');
    }
    //商户开票商品列表
    public function invoicing_list(Request $request){
        $params = $request->all();
        $user = auth('support')->user();
        $where = [];
        if (empty($params['merchant_num'])){
            return $this->sendError('请传入商户号');
        }
        if (!empty($params['goods_name'])){
            $where[] = ['goods_name','like','%'.$params['goods_name'].'%'];
        }
        if (!empty($params['goods_id'])){
            $where[] = ['id','=',$params['goods_id']];
        }
        if (!empty($params['brand_id'])) {
            $strs = 'pid';
            $b = $params['brand_id'];
        } else {
            $strs = 'level';
            $b = 3;
        }
        $brand_ids = [];
        $brandrealid = XuGoodsBrand::where($strs, $b)->select('category_id')->get();
        $brand_idinfo = json_decode(json_encode($brandrealid), true);
        foreach ($brand_idinfo as $k => $v) {
            $brand_ids[] = $v['category_id'];
        }
        $res =  XnSupplierGoods::
              whereIn('brand_id', $brand_ids)
            ->where('release',1)
            ->where($where)
            ->select('goods_name','unit_price','goods_belong','id as goods_id','price','release','brand_id','o_type')
            ->orderby('price')
            ->orderBy('brand_id')
            ->paginate(10);
        $res = json_decode(json_encode($res), true);
        foreach ($res['data'] as $k=>$v){
            $merchant = XnMerchantGoodsInvoicing::where(['merchant_num'=>$params['merchant_num'],'goods_id'=>$v['goods_id']])->first();
            $merchant = json_decode(json_encode($merchant), true);
            $res['data'][$k]['status'] = 2;
            if (!empty($merchant['price'])){
                $res['data'][$k]['price'] = $merchant['price'];
                $res['data'][$k]['status'] = 1;
            }
            $res['data'][$k]['official_price'] = $merchant['official_price']??'';
            $res['data'][$k]['timing_is_up'] = $merchant['timing_is_up']??2;//定时上下架状态
            $res['data'][$k]['id'] = $merchant['id']??'';//定时上下架id
            $redis = new \redis();
            $redis->connect('127.0.0.1', 6379);//连接redis
            $key = $user->business_number.$params['merchant_num'].'MerchantGoodsTimePrice'.$v['goods_id'];
//            var_dump($key);
            $res['data'][$k]['merchant_goods_regular_price'] = json_decode($redis->get($key),true)??'';//查询
            if ($v['o_type'] != 0){
                $res['data'][$k]['goods_belong'] = XnGoodsCarmyType::where('type',$v['goods_belong'])->value('name');
            }else{
                $res['data'][$k]['goods_belong'] = InterfaceConfiguration::where('id',$v['goods_belong'])->value('title');
            }
        }
        if (!$res){
            return $this->sendError('查询失败');
        }
        return $this->sendResponse($res, '查询成功！');
    }
    //供应商设置开票商品价格
    public function invoicing_edit(Request $request){
        $params = $request->all();
        $array = [
            'merchant_num'=>$params['merchant_num'],
            'goods_id'=>$params['goods_id'],
            'price'=>$params['price'],
            'official_price'=>$params['official_price'],
        ];
        $goodsinfo = XnMerchantGoodsInvoicing::where('merchant_num',$params['merchant_num']) -> where('goods_id',$params['goods_id'])->first();
        $goodsinfo = json_decode(json_encode($goodsinfo), true);
        if(!$goodsinfo){
            $res = XnMerchantGoodsInvoicing::insert($array);
        }else{
            $res =XnMerchantGoodsInvoicing::where('id',$params['id'])->update($array);
        }
        if (!$res){
            return $this->sendError('修改失败');
        }
        return $this->sendResponse([], '修改成功');
    }
    //开票商品关联子商品列表
    public function invoicing_association(Request $request){
        $params = $request->all();
        $search = $request->post('search','');
        $where = [];
        if (isset($search['keyword']) && !empty($search['keyword'])) {
            $where = function($query) use($search){
                $query->where('g.goods_name', 'like', '%'.$search['keyword'].'%')
                    ->orWhere('g.Supplier_status', 'like', '%'.$search['keyword'].'%')
                    ->orWhere('g.goods_id', 'like', '%'.$search['keyword'].'%');
            };
        }
        $brand_id =  XnSupplierGoods::where('id',$params['goods_id'])->value('brand_id');
//        DB::connection()->enableQueryLog();
        $res = Db::connection( request()->get('db', null))->table('xn_supplier_goods as g')
            ->leftjoin('xn_supplier_goods_merchant_relation as r', function($join) use ($params) {
                $join->on('g.id', '=', 'r.r_gid')->where('r.g_id', '=', $params['goods_id'])->where('r.merchant_num',$params['merchant_num']);
            })
            ->where('g.goods_belong', '!=', 2)
            ->where('g.goods_belong', '!=', 3)
            ->where('g.is_up', '=', 1)
            ->where('g.release', '!=', 3)
            ->where('g.goods_belong','!=',0)
            ->where('g.brand_id','=',$brand_id)
            ->where($where)
            ->orderBy('g.unit_price')
            ->when($params['type'], function($query) use($params){
                return $params['type'] == 2 ? $query->whereNull('r.id') : $query->whereRaw('IF(ISNULL(r.id), false, true)')->orderBy('r.sort','desc');
            })
            ->select('g.o_type','g.goods_name','r.percentage','r.sort','r.id as r_id','g.id', 'g.goods_name','g.goods_code', 'g.unit_price', 'g.goods_belong', 'g.max_price', 'g.release', Db::raw('IF(ISNULL(r.id), 2 , 1) as is_relation'))
            ->paginate(10);
//        $res = DB::getQueryLog();
        $percentage_s = 0;
        $res = json_decode(json_encode($res),true);
        foreach ($res['data'] as $k=>$v){
            $res['data'][$k]['percentage_s'] = ($percentage_s+$v['percentage']);
            if ($v['o_type'] != 0){
                $res['data'][$k]['goods_belong'] = XnGoodsCarmyType::where('type',$v['goods_belong'])->value('name');
            }else{
                $res['data'][$k]['goods_belong'] = InterfaceConfiguration::where('id',$v['goods_belong'])->value('title');
            }
        }
        if (!$res){
            return $this->sendError('查询失败');
        }
        return $this->sendResponse($res, '查询成功');
    }
    //开票商品关联子商品操作
    public function invoicing_association_edit(Request $request){
        $params = $request->all();
        if (empty($params['type'])){
            return $this->sendError('操作状态不能为空');
        }
        if (empty($params['g_id'])){
            return $this->sendError('商品id不能为空');
        }
        if (empty($params['r_gid'])){
            return $this->sendError('被关联商品id不能为空');
        }
        if (empty($params['merchant_num'])){
            return $this->sendError('商户号不能为空');
        }
        if ($params['type'] == 1){
            $array = [
                'g_id'=>$params['g_id'],
                'r_gid'=>$params['r_gid'],
                'merchant_num'=>$params['merchant_num'],
            ];
            $status = XnSupplierGoodsMerchantRelation::where(['g_id'=>$params['g_id'],'r_gid'=>$params['r_gid'],'merchant_num'=>$params['merchant_num']])->first();
            if (!empty($status)){
                return $this->sendError('该商品已经关联');
            }
            $res = XnSupplierGoodsMerchantRelation::insert($array);
            if (!$res){
                return $this->sendError('关联失败');
            }
            return  $this->sendResponse([],'关联成功');
        }elseif ($params['type'] ==2 ){
            $res = XnSupplierGoodsMerchantRelation::where('id',$params['r_id'])->delete();
            if (!$res){
                return $this->sendError('操作频繁');
            }
            return  $this->sendResponse([],'取消成功');
        }
        return $this->sendError('参数无效');
    }
    //开票子商品置顶
    public function invoicing_child_goods_topping(Request $request){
        $params = $request->all();
        if (empty($params['r_id'])){
            return $this->sendError('id不能为空');
        }

        $res = XnSupplierGoodsMerchantRelation::where('id',$params['r_id'])->update(['sort'=>$params['type']]);
        if (!$res){
            return $this->sendError('操作失败');
        }
        return $this->sendResponse([],'操作成功');
    }
    //开票子商品设置百分比
    public function invoicing_child_goods_percentage(Request $request){
        $params = $request->all();
        $row = XnSupplierGoodsMerchantRelation::where('id',$params['r_id'])->first();

        if (!$row) {
            return $this->sendError('设置失败');
        }
        $row = collect($row)->toArray();
        if ($row['percentage'] == $params['percentage']) {
            return $this->sendError('未做更改');
        }
        DB::connection(request()->get('db', 'supplier'))->beginTransaction();
        try {
            $res = XnSupplierGoodsMerchantRelation::where('id',$row['id'])->update(['percentage'=>$params['percentage']]);
            if (!$res){
                throw new \Exception('设置失败');
            }
            CyclePercentage::where('pid', $row['r_gid'])
                ->where('role', 1)
                ->delete();

            DB::connection(request()->get('db', 'supplier'))->commit();

        } catch (\Throwable $e) {
            DB::connection(request()->get('db', 'supplier'))->rollBack();
            return $this->sendError($e->getMessage());
        }
        return $this->sendResponse([],'设置成功');
    }
    //供应商设置开票商品定时改价
    public function invoicing_regular_price(Request $request){
        $params = $request->all();
        $user = auth('support')->user();//获取供应商信息
        $startDate =date('Y-m-d H:i:s');//现在的时间
        $endDate = $params['time'];//要修改的时间
        $time=floor((strtotime($endDate)-strtotime($startDate)));
        $str = strpos($time,'-');
        if ($str === 0){
            return $this->sendError('请选择正确的时间');
        }
        $data = [
            'id'=>$params['id'],//商品id
            'price'=>$params['price'],//销售价
            'business_number'=>$user->business_number,
            'merchant_num'=>$params['merchant_num'],
            'db'=>request()->get('db', 'supplier')
        ];

        $redis = new \redis();
        $redis->connect('127.0.0.1', 6379);//连接redis
        $info = [
            'id'=>$params['id'],//商品id
            'price'=>$params['price'],//销售价
            'time'=>$endDate,
            'business_number'=>$user->business_number,
            'merchant_num'=>$params['merchant_num'],
        ];
        $key = $user->business_number.$data['merchant_num'].'MerchantGoodsTimePrice'.$data['id'];
        $value = json_encode($info);//用手机号作为v值
        $redis->set($key, $value, 86400);//设置的24小时有效期
        MerchantGoodsTimePrice::dispatch($data)->delay(Carbon::now()->addSeconds($time))->onConnection('redis')->onQueue('MerchantGoodsTimePrice');
        return $this->sendResponse([],'将在'.$endDate.'修改此商品价格');
    }
    //供应商撤销开票商品定时改价
    public function invoicing_regular_price_revoke(Request $request){
        $params = $request->all();
        $user = auth('support')->user();//获取供应商信息
        $redis = new \redis();
        $redis->connect('127.0.0.1', 6379);//连接redis
        $key = $user->business_number.$params['merchant_num'].'MerchantGoodsTimePrice'.$params['id'];
        $redis->del($key);//删除定时的key
        return $this->sendResponse([],'撤销成功');
    }
    //供应商设置开票商品定时上下架
    public function invoicing_regular_release(Request $request){
        $params = $request->all();
        $where = ['goods_id'=>$params['goods_id'],'merchant_num'=>$params['merchant_num']];
        if ($params['status'] == 2){
            XnMerchantGoodsTimeIsUp::where($where)->delete();
            XnMerchantGoodsInvoicing::where($where)->update(['timing_is_up'=>2,'release'=>1]);
            return $this->sendResponse([],'设置成功');
        }
        $goods_m =  XnMerchantGoodsInvoicing::where($where)->first();
        $goods_m = json_decode(json_encode($goods_m),true);
        if (empty($goods_m)){
            return $this->sendError('请先设置价格');
        }
        $day = explode(',',$params['day']);
        if ($params['status'] == 1 && empty($params['day'])){
            return $this->sendError('请选择时间周期');
        }
        XnMerchantGoodsTimeIsUp::where($where)->delete();
        if (empty($params['day'])){
            return $this->sendResponse([],'设置成功');
        }
        $array = [];
        foreach ($day as $k=>$v){
            $data = [
                'goods_id'=>$params['goods_id'],
                'day'=>$v,
                'shelftime'=>strtotime($params['shelftime']),
                'offshelftime'=>strtotime($params['offshelftime']),
                'type'=>$params['type'],
                'merchant_num'=>$params['merchant_num'],
            ];
            $array[] = $data;
        }
        XnMerchantGoodsInvoicing::where($where)->update(['timing_is_up'=>$params['status']]);
        $res =XnMerchantGoodsTimeIsUp::insert($array);
        if (!$res){
            return $this->sendError('设置失败');
        }else{
            $week = date("w");
            $info = XnMerchantGoodsTimeIsUp::where('day',$week)->where($where)->first();
            $info = json_decode(json_encode($info),true);
//            var_dump($info);
            if (!empty($info)){
                $time = date('H:i:s',time());//当前时间
                $start_time = date('H:i:s', $info['shelftime']);
                $end_time = date('H:i:s',$info['offshelftime']);

                $Remaining_time1 = strtotime($start_time) - strtotime($time);
                $Remaining_time2 = strtotime($end_time) - strtotime($time);
                $data1 = [];
                $data2 = [];
                $goodsInfo = XnMerchantGoodsInvoicing::where($where)->first();
                if ($goodsInfo['release'] == 0){
                    return $this->sendResponse([],'设置成功');
                }
                if ($info['type'] == 1){ //维护时间
                    if ($goodsInfo['release'] == 1){
                        $res = $this->rangeTime($start_time,$end_time);
                        if ($res == true){
                            XnMerchantGoodsInvoicing::where($where)->update(['release'=>2]);
                        }
                    }elseif ($goodsInfo['release'] == 2){
                        $res = $this->rangeTime($start_time,$end_time);
                        if ($res == false){
                            XnMerchantGoodsInvoicing::where($where)->update(['release'=>1]);
                        }
                    }
                    $data1 = [
                        'goods_id'=>$info['goods_id'],
                        'status'=>2,
                        'merchant_num'=>$params['merchant_num'],
                        'db'=>request()->get('db', 'supplier')
                    ];
                    $data2 = [
                        'goods_id'=>$info['goods_id'],
                        'status'=>1,
                        'merchant_num'=>$params['merchant_num'],
                        'db'=>request()->get('db', 'supplier')
                    ];
                    MerchantGoodsTimeIsUp::dispatch($data2)->delay(Carbon::now()->addSeconds($Remaining_time2))->onConnection('redis')->onQueue('MerchantGoodsTimeIsUp');//下架时间
                }
                if ($info['type'] == 2){
                    if ($goodsInfo['release'] == 1){
                        $res = $this->rangeTime($start_time,$end_time);
                        if ($res == false){
                            XnMerchantGoodsInvoicing::where($where)->update(['release'=>2]);
                        }
                    }elseif($goodsInfo['release'] == 2){
                        $res = $this->rangeTime($start_time,$end_time);
                        if ($res == true){
                            XnMerchantGoodsInvoicing::where($where)->update(['release'=>1]);
                        }
                    }
                    $data1 = [
                        'goods_id'=>$info['goods_id'],
                        'status'=>1,
                        'merchant_num'=>$params['merchant_num'],
                        'db'=>request()->get('db', 'supplier')
                    ];
                    $data2 = [
                        'goods_id'=>$info['goods_id'],
                        'status'=>2,
                        'merchant_num'=>$params['merchant_num'],
                        'db'=>request()->get('db', 'supplier')
                    ];
                    MerchantGoodsTimeIsUp::dispatch($data2)->delay(Carbon::now()->addSeconds($Remaining_time2))->onConnection('redis')->onQueue('MerchantGoodsTimeIsUp');//下架时间
                }
                if ($info['type'] == 0){
                    return $this->sendResponse([],'设置成功');
                }
                if ($Remaining_time1 < 0 || $Remaining_time2< 0){
                    return $this->sendResponse([],'设置成功');
                }
                MerchantGoodsTimeIsUp::dispatch($data1)->delay(Carbon::now()->addSeconds($Remaining_time1))->onConnection('redis')->onQueue('MerchantGoodsTimeIsUp');//上架时间
                MerchantGoodsTimeIsUp::dispatch($data2)->delay(Carbon::now()->addSeconds($Remaining_time2))->onConnection('redis')->onQueue('MerchantGoodsTimeIsUp');//下架时间
            }
            return $this->sendResponse([],'设置成功');
        }
    }
    //供应商设置开票商品定时上下架列表
    public function invoicing_regular_release_list (Request $request){
        $params = $request->all();
        $where = ['goods_id'=>$params['goods_id'],'merchant_num'=>$params['merchant_num']];
        $goods = XnMerchantGoodsInvoicing::where($where)->value('timing_is_up');
        $res = XnMerchantGoodsTimeIsUp::where($where)->get();
        $res = json_decode(json_encode($res),true);
        if (empty($res)){
            return $this->sendError('没有设置');
        }
        $week = [];
        foreach ($res as $k=>$v){
            $week[] = $v['day'];
            $res['shelftime'] = $v['shelftime'];
            $res['offshelftime'] = $v['offshelftime'];
            $res['type'] = $v['type'];
        }
        $data = [
            'week'=>implode(',',$week),
            'shelftime'=>date('H:i:s', $res['shelftime']),
            'offshelftime'=>date('H:i:s',$res['offshelftime']),
            'type' => $res['type'],
            'timing_is_up'=>$goods
        ];

        if (!$res){
            return $this->sendError('没有设置');
        }else{
            return $this->sendResponse($data,'查询成功');
        }
    }
    //全充值商品关联列表
    public function allrechargelist(Request $request){
        $params = $request->all();
        $search = $request->post('search','');
        $where = [];
        if (isset($search['keyword']) && !empty($search['keyword'])) {
            $where = function($query) use($search){
                $query->where('g.goods_name', 'like', '%'.$search['keyword'].'%')
                    ->orWhere('g.goods_belong', 'like', '%'.$search['keyword'].'%')
                    ->orWhere('g.goods_code', 'like', '%'.$search['keyword'].'%');
            };
        }
        $brand_id =  XnSupplierGoods::where('id',$params['goods_code'])->value('brand_id');
        if ($params['type_r'] == 1){
            $where_r = ['r.merchantnum'=>$params['merchantnum'],'r.gid'=>$params['goods_code'],'r.type'=>1];
        }else{
            $where_r = ['r.gid'=>$params['goods_code'],'r.type'=>2];
        }
//        DB::connection()->enableQueryLog();
        $res = Db::connection( request()->get('db', null))->table('xn_supplier_goods as g')
            ->leftjoin('xn_supplier_goods_fully_charged_relation as r', function($join) use ($where_r) {
                $join->on('g.id', '=', 'r.child_gid')->where($where_r);
            })
            ->where('g.goods_belong', '!=', 2)
            ->where('g.goods_belong', '!=', 3)
            ->where('g.is_up', '=', 1)
            ->where('g.brand_id','=',$brand_id)
            ->where('g.release','=',1)
            ->where('g.goods_type','=',1)
            ->where($where)
            ->orderBy('g.unit_price')
            ->when($params['type'], function($query) use($params){
                return $params['type'] == 2 ? $query->whereNull('r.id') : $query->whereRaw('IF(ISNULL(r.id), false, true)');
            })
            ->select('r.id as r_id','g.id', 'g.goods_name','g.o_type','g.goods_code', 'g.unit_price', 'g.goods_belong', 'g.max_price', 'g.release', Db::raw('IF(ISNULL(r.id), 2 , 1) as is_relation'))
            ->get();
//        $res = DB::getQueryLog();
        $res = json_decode(json_encode($res),true);
        foreach ($res as $k=>$v){
            if ($v['o_type'] != 0){
                $res[$k]['goods_belong'] = XnGoodsCarmyType::where('type',$v['goods_belong'])->value('name');
            }else{
                $res[$k]['goods_belong'] = InterfaceConfiguration::where('id',$v['goods_belong'])->value('title');
            }
        }
        $total = count($res);
        if (!$res){
            return $this->sendError('查询失败');
        }
        return $this->sendResponse(['total'=>$total,'data'=>$res], '查询成功');
    }
    //全充值商品关联列表
    public function allrecharge_association(Request $request){
        $params = $request->all();
        $gid = $params['gid'] ?? 0;
        $cgid = $params['cgid'] ?? 0;
        $type = $params['type']?? 0;
        $merchant_number = $params['merchant_number'] ?? 0;
        if ($gid == 0 || $cgid == 0 || $type == 0) {
            return $this->sendError('参数错误');
        }
        // 判断主商品是否存在
        $g_goods = XnSupplierGoods::where('id', $gid)->first();
        if (!$g_goods) {
            return $this->sendError('主商品不存在');
        }
        $c_goods = XnSupplierGoods::where('id', $cgid)->first();
        if (!$c_goods) {
            return $this->sendError('子商品不存在');
        }
        $data = [
            'gid'           => $gid,
            'child_gid'          => $cgid,
            'type'=>$type,
            'create_time'   => date('Y-m-d H:i:s',time())
        ];
        if($type == 1){
            $data['merchantnum'] = $merchant_number;
        }
        // 查询是否已关联
        $relation_goods = XnSupplierGoodsFullyChargedRelation::where('gid', $gid)->where('child_gid', $cgid)->first();
        if ($relation_goods) {
            // 取消关联
            $res = XnSupplierGoodsFullyChargedRelation::where('gid', $gid)->where('child_gid', $cgid)->delete();
        } else {
            // 添加关联商品
            $res = XnSupplierGoodsFullyChargedRelation::insert($data);
        }
        if (!$res){
            return $this->sendError('操作失败');
        }
        return $this->sendResponse([], '操作成功');
    }

}
